package com.troubadorian.feeds;

import android.content.Context;
import android.content.SharedPreferences;
import android.util.Log;

import com.fivehundredpixels.fivehundredpixels.model.FetchPhotoResponse;
import com.fivehundredpixels.fivehundredpixels.models.FetchPhotosResponse;
import com.fivehundredpixels.fivehundredpixels.model.Photo;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Type;
import java.util.List;

public class DataManager
{

	private static final String TAG = "DataManager";

	private static HttpClient httpclient = new DefaultHttpClient();

	private static DataManager instance;

	public static DataManager getInstance()
	{
		if (instance == null)
		{
			instance = new DataManager();
		}
		return instance;
	}
	/*

	public String clientAPIUserRequestSignin(Context context, String email,
			String password)
	{

		Log.d(TAG, "---------clientAPIUserRequestSignin---------");

		String jsonFileUrl = FeaturesConfiguration.mUrlSignIn;

		HttpEntity entity = sendRequestGetResponse(context, jsonFileUrl,
				"Email", email, "Password", password);

		InputStream source = null;

		try
		{
			source = entity.getContent();
		} catch (Exception ex)
		{
			Log.e(TAG, ex.toString());
		}

		Reader reader = new InputStreamReader(source);

		Gson gson = new Gson();

		Type responseType = new TypeToken<LoginResponse>()
		{

		}.getType();

		LoginResponse loginResponse;

		loginResponse = gson.fromJson(reader, responseType);

		return loginResponse.getSuccess();

	}

	public String clientAPIUserRequestSignout(Context context,
			String cookieString)
	{

		String jsonFileUrl = FeaturesConfiguration.mUrlSignOut;

		HttpEntity entity = sendRequestGetResponse(context, jsonFileUrl, null,
				null, null, null);

		InputStream source = null;

		try
		{
			source = entity.getContent();
		} catch (Exception ex)
		{
			Log.e(TAG, ex.toString());
		}

		Reader reader = new InputStreamReader(source);

		Gson gson = new Gson();

		Type responseType = new TypeToken<LoginResponse>()
		{

		}.getType();

		LoginResponse loginResponse;

		loginResponse = gson.fromJson(reader, responseType);

		return loginResponse.getSuccess();

	}
	*/

	public String clientAPIUserRequestChangePassword(String password)
	{
		return "OK";
	}

	public String clientAPIUserSettingsRequestGet()
	{

		return "OK";
	}

	public String clientAPIUserSettingsRequestUpdate(int inactivityPeriodId)
	{

		return "OK";
	}
	
	
	

	public int fetchPhotosResponseResultByPost(Context context)
	{
		String jsonFileUrl = FeaturesConfiguration.popularURL;

		HttpEntity entity = sendPostRequestByPostGetResponse(context, jsonFileUrl,
				"Email", "", "Password", "");

		InputStream source = null;

		try
		{
			source = entity.getContent();
		} catch (Exception ex)
		{
			Log.e(TAG, ex.toString());
		}

		Reader reader = new InputStreamReader(source);

		Gson gson = new Gson();

		Type responseType = new TypeToken<FetchPhotosResponse>()
		{

		}.getType();

		FetchPhotosResponse fetchPhotosResponse = gson.fromJson(reader,
				responseType);

		return fetchPhotosResponse.current_page;
	}
	
	public Photo fetchPhotoByGet(Context context, String jsonFileUrl, boolean fromCache)
	{
		FetchPhotoResponse fetchPhotoResponse;

		InputStream source = retrieveStream(jsonFileUrl);

		Reader reader = new InputStreamReader(source);

		Gson gson = new Gson();

		Type responseType = new TypeToken<FetchPhotoResponse>() {

		}.getType();

		fetchPhotoResponse = gson.fromJson(reader, responseType);

		Log.d(TAG, "------photos----" + fetchPhotoResponse.photo.id);

		return fetchPhotoResponse.photo;
	}
	
	public List<com.fivehundredpixels.fivehundredpixels.models.Photo> fetchPhotosByGet(Context context, String jsonFileUrl, boolean fromCache)
	{
		FetchPhotosResponse fetchPhotosResponse;

		InputStream source = retrieveStream(jsonFileUrl);

		Reader reader = new InputStreamReader(source);

		Gson gson = new Gson();

		Type responseType = new TypeToken<FetchPhotosResponse>() {

		}.getType();

		fetchPhotosResponse = gson.fromJson(reader, responseType);

		Log.d(TAG, "------photos----" + fetchPhotosResponse.photos.get(0).name);

		return fetchPhotosResponse.photos;
	}
	

	public List<com.fivehundredpixels.fivehundredpixels.models.Photo> fetchPhotosByPost(Context context, boolean fromCache)
	{
		String jsonFileUrl = FeaturesConfiguration.popularURL;
		
		HttpEntity entity = sendPostRequestByPostGetResponse(context, jsonFileUrl,
				"Email", "", "Password", "");

		InputStream source = null;
		try
		{
			source = entity.getContent();
		} catch (Exception ex)
		{
			Log.e(TAG, ex.toString());
		}


		Reader reader = new InputStreamReader(source);

		Gson gson = new Gson();

		Type responseType = new TypeToken<FetchPhotosResponse>()
		{

		}.getType();

		FetchPhotosResponse fetchPhotosResponse = gson.fromJson(reader,
				responseType);

		return fetchPhotosResponse.photos;

	}

	private static HttpEntity sendPostRequestByPostGetResponse(Context context,
			String jsonFileUrl, String paramKey1, String paramValue1,
			String paramKey2, String paramValue2)
	{

		HttpPost post = new HttpPost(jsonFileUrl);

		post.setHeader("Content-type", "application/json");

		post.setHeader("Accept", "application/json");

		JSONObject obj = new JSONObject();

		try
		{
			if (paramKey1 != null && paramValue1 != null)
			{
				obj.put(paramKey1, paramValue1);
			}
			if (paramKey2 != null && paramValue2 != null)
			{
				obj.put(paramKey2, paramValue2);
			}

		} catch (JSONException ex)
		{
			Log.e(TAG, ex.toString());
		}
		try
		{
			post.setEntity(new StringEntity(obj.toString(), "UTF-8"));

		} catch (UnsupportedEncodingException ex)
		{
			Log.e(TAG, ex.toString());
		}

		HttpResponse httpResponse = null;

		try
		{
			httpResponse = httpclient.execute(post);

		} catch (IOException ex)
		{
			Log.e(TAG, ex.toString());
		}

		HttpEntity entity = httpResponse.getEntity();

		return entity;
	}

	private static String convertStreamToString(InputStream is)
	{

		BufferedReader reader = new BufferedReader(new InputStreamReader(is));
		StringBuilder sb = new StringBuilder();

		String line = null;
		try
		{
			while ((line = reader.readLine()) != null)
			{
				sb.append((line + "\n"));
			}
		} catch (IOException e)
		{
			e.printStackTrace();
		} finally
		{
			try
			{
				is.close();
			} catch (IOException e)
			{
				e.printStackTrace();
			}
		}
		return sb.toString();
	}
	private static InputStream retrieveStream(String url)
	{

		DefaultHttpClient client = new DefaultHttpClient();

		HttpGet getRequest = new HttpGet(url);

		try
		{

			HttpResponse getResponse = client.execute(getRequest);
			final int statusCode = getResponse.getStatusLine().getStatusCode();

			if (statusCode != HttpStatus.SC_OK)
			{
				Log.w(TAG, "Error " + statusCode + " for URL " + url);
				return null;
			}

			HttpEntity getResponseEntity = getResponse.getEntity();
			return getResponseEntity.getContent();

		} catch (IOException e)
		{
			getRequest.abort();
			Log.d(TAG, "Error for URL " + url, e);
		}

		return null;

	}

}
